package test.h0815;

import java.util.ArrayList;
import java.util.Scanner;

public class Main3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();
        int[][] graph = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                graph[i][j] = sc.nextInt();
            }
        }

        System.out.println(getResult(graph));
    }

    private static int getResult(int[][] graph) {
        int rows = graph.length;
        int cols = graph[0].length;

        UnionFindSet ufs = new UnionFindSet(rows * cols);

        ArrayList<Integer> huawei = new ArrayList<>(); //记录小华小为的位置
        ArrayList<Integer> restaurants = new ArrayList<>();// 记录餐厅的位置

        //往上下左右四个方向，使得和小华小为的位置在同一个并查集中。
        int[][] offsets = {
                {-1, 0},
                {1, 0},
                {0, -1},
                {0, 1}
        };
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                int pos = i * rows + j;
                if (graph[i][j] == 2) {
                    huawei.add(pos);
                }
                //餐厅
                if (graph[i][j] == 3) {
                    restaurants.add(pos);
                }
                //1代表障碍
                for (int k = 0; k < offsets.length; k++) {
                    int newI = i + offsets[k][0];
                    int newJ = j + offsets[k][1];
                    if (newI >= 0 && newI < rows && newJ >= 0 && newJ < cols && graph[newI][newJ] != 1) {
                        //放在一个集合中
                        ufs.union(pos, newI * rows + newJ);
                    }
                }
            }
        }
        int p1 = ufs.findParent(huawei.get(0));
        int p2 = ufs.findParent(huawei.get(1));
        if (p1 != p2) {
            return 0;
        }
        int ans = 0;
        for (Integer restaurant : restaurants) {
            if (ufs.findParent(restaurant) == p1) {
                ans++;
            }
        }
        return ans;
    }

    static class UnionFindSet {
        int[] fa;

        public UnionFindSet(int n) {
            fa = new int[n];
            for (int i = 0; i < n; i++) {
                fa[i] = i;
            }
        }

        public int findParent(int x) {
            if (x == fa[x]) {
                return x;
            }
            return fa[x] = findParent(fa[x]);
        }

        //合并 TODO 注意合并的写法
        public void union(int x, int y) {
            int a = findParent(x);
            int b = findParent(y);
            if (a != b) {
                fa[a] = b;
            }
        }
    }
}
